package com.hyk.commonLib.common.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by 贺玉琨 on 2019/6/4.
 */
public class ListUtils {
    @SafeVarargs
    public static <T> List<T> asList(T... items) {
        return new ArrayList<>(Arrays.asList(items));
    }

    public static boolean isEmpty(List<?> list) {
        return list == null || list.isEmpty();
    }

    public static boolean notEmpty(List<?> list) {
        return !isEmpty(list);
    }

    public static <T> T last(List<T> list) {
        return isEmpty(list) ? null : list.get(list.size() - 1);
    }

    public static <T> List<T> filter(List<T> list, Filter<T> filter) {
        List<T> result = new ArrayList<>();
        if (isEmpty(list)) return result;
        for (T t : list) {
            if (filter.filter(t)) result.add(t);
        }
        return result;
    }

    public static <T> T getRandomItem(List<T> list ) {
        return isEmpty(list) ? null : list.get(RandomUtils.getRandom(0, list.size()));
    }

    public static <T> List<T> moveHeaderToTail(List<T> list) {
        return moveHeaderToTail(list, 1);
    }

    public static <T> List<T> moveHeaderToTail(List<T> list, int count) {
        if (list == null || list.size() <= count) {
            return list;
        }
        List<T> partOne = list.subList(0, count);
        List<T> partTwo = list.subList(count, list.size());
        ArrayList<T> newList = new ArrayList<>(partTwo);
        newList.addAll(partOne);
        return newList;
    }

    public interface Filter<T> {
        /**
         * @return 返回false代表移除本项，true代表保留本项
         */
        boolean filter(T item);
    }
}
